package com.dondedesigns.eh.controller.index;

import com.dondedesigns.eh.persistence.ApprovedStatus;
import com.dondedesigns.eh.persistence.User;
import com.dondedesigns.eh.persistence.dao.UserDAO;
import com.dondedesigns.eh.util.MessageConstants;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

public class Register extends ActionSupport implements ModelDriven<User>{
	
	private User user = new User();
	
	private UserDAO userDAO = null;
	
	@Override
	public String input() throws Exception {
		return SUCCESS;
	}
	
	@Override
	public String execute() throws Exception {
		user.setApprovedStatus(ApprovedStatus.APPROVED);
		userDAO.save(user);
		addActionMessage(MessageConstants.REGISTER_SUCCESSFUL);
		return SUCCESS;
	}

	@Validations(
			requiredFields = {
				@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName="email", message=MessageConstants.EMAIL_REQUIRED),
				@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName="username"),
				@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName="name", message=MessageConstants.NAME_REQUIRED),
				@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName="password", message=MessageConstants.PASSWORD_REQUIRED)
			},
			emails = {
				@EmailValidator(type = ValidatorType.SIMPLE, fieldName="email", message=MessageConstants.EMAIL_ERROR)
			},
			regexFields = {
				@RegexFieldValidator (type = ValidatorType.SIMPLE, fieldName="username", message=MessageConstants.USERNAME_ERROR, expression="[\\w]+")
			}
	)
	@Override
	public User getModel() {
		return user;
	}
	
	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	/*@Override
	public void validate() {
		if (userDAO.emailExists(user)) {
			addActionError(getText(MessageConstants.EMAIL_EXISTS));
		}
		if (user.getPassword().equals("") || user.getConfirmPassword().equals("")) {
			addActionError(getText(MessageConstants.PASSWORD_REQUIRED));
		} else if (!user.getPassword().equals(user.getConfirmPassword())) {
			addActionError(getText(MessageConstants.PASSWORD_MISMATCH));
		}
	}*/
	
}
